package com.onlinepay.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @Author: linjl
 * @Date: 2025/3/13 15:46
 * @Description:
 */
public class KeyPairExample {

    public static void main(String[] args) {
        try {
            // 创建 KeyPairGenerator 实例，指定算法为 RSA
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥长度
            keyPairGenerator.initialize(512);
            // 生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            // 获取公钥和私钥
            byte[] publicKey = keyPair.getPublic().getEncoded();
            byte[] privateKey = keyPair.getPrivate().getEncoded();

            // 将密钥转换为 Base64 编码字符串
            String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey);
            String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKey);

            // 输出公钥和私钥
            System.out.println("Public Key:");
            System.out.println(publicKeyBase64);
            System.out.println("Private Key:");
            System.out.println(privateKeyBase64);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
